import BackgroundTimer from 'react-native-background-timer';
import { Platform } from 'react-native';

// 后台定时器集合
export const timerMap = new Map();

const backgroundTimePlugin = {
  setTimer: ({key, type, time, callback} = {
    key: '',
    type: '',
    time: 60,
    callback: null
  }) => {
    logger('[BackgroundTimer][setTimer]', key, type)
    if (!callback) {
      return
    }
    if (type === 'interval') {
      timerMap.set(key, {type, timerIndex: BackgroundTimer.setInterval(callback, time)})
    } else if (type === 'timeout') {
      timerMap.set(key, {type, timerIndex: BackgroundTimer.setTimeout(callback, time)})
    }
  },
  init: () => {
    if (Platform.OS == "ios") {
      BackgroundTimer.start()
      logger('[BackgroundTimer][init]ios-start')
    }
  },
  reset: () => {
    if (Platform.OS == "ios") {
      BackgroundTimer.stop()
      logger('[BackgroundTimer][init]ios-stop')
    }
  },
  clear: function() {
    timerMap.forEach((val, key) => {
      if (val.type === 'interval') {
        backgroundTimePlugin.remove({key, type: 'interval'})
      } else if (val.type === 'timeout') {
        backgroundTimePlugin.remove({key, type: 'timeout'})
      }
    })
  },
  remove: ({key, type} = {}) => {
    logger('[BackgroundTimer][remove]', key, type)
    const data = timerMap.get(key)
    if (data) {
      if (type === 'interval') {
        BackgroundTimer.clearInterval(data.timerIndex)
      } else if (type === 'timeout') {
        BackgroundTimer.clearTimeout(data.timerIndex)
      }
      timerMap.delete(key)
    }
  }
}

export default backgroundTimePlugin